package com.behome.socket_proxy.Controller;

import com.behome.socket_proxy.config.Result;
import com.behome.socket_proxy.netty_D.Constants;
import com.behome.socket_proxy.netty_D.client.NettyClient;
import com.behome.socket_proxy.netty_D.server.StandardDNettyServer;
import io.netty.channel.Channel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * DataController
 *
 * @author bh_ljy
 * @version 2024/05/27 17:18
 **/
@RestController
public class DataController {
    @GetMapping("/getServerInfo")
    public Result getServerInfo() {
        ResultServer resultServer = new ResultServer();
        ServerInfo primary_server = new ServerInfo();
        primary_server.setIp(Constants.proxy1);
        primary_server.setPort(Constants.port);
        NettyClient nettyClient = new NettyClient(null, primary_server.getIp(), primary_server.getPort());
        Channel channel = nettyClient.getChannel();
        if (channel != null && channel.isActive()) {
            primary_server.setStatus(1);
        } else {
            primary_server.setStatus(0);
        }
        resultServer.setPrimary_server(primary_server);
        ServerInfo backup_server = new ServerInfo();
        backup_server.setIp(Constants.proxy2);
        backup_server.setPort(Constants.port);
        NettyClient nettyClient2 = new NettyClient(null, backup_server.getIp(), backup_server.getPort());
        Channel channel2 = nettyClient2.getChannel();
        if (channel2 != null && channel2.isActive()) {
            backup_server.setStatus(1);
        } else {
            backup_server.setStatus(0);
        }
        resultServer.setBackup_server(backup_server);
        return Result.succeed("获取连接服务器成功!", resultServer);
    }

    @PostMapping("/setServerInfo")
    public Result setServerInfo(@RequestBody ResultServer resultServer) throws InterruptedException {
        if (Constants.port != resultServer.getPrimary_server().getPort()) {
            StandardDNettyServer.getInstance().stop();
            StandardDNettyServer.getInstance().start();
            Constants.port = resultServer.getPrimary_server().getPort();
        }
        Constants.proxy1 = resultServer.getPrimary_server().getIp();
        if (Constants.port != resultServer.getBackup_server().getPort()) {
            StandardDNettyServer.getInstance().stop();
            StandardDNettyServer.getInstance().start();
            Constants.port = resultServer.getPrimary_server().getPort();
        }
        Constants.proxy2 = resultServer.getBackup_server().getIp();
        return Result.succeed("设置连接服务器成功!");
    }

}
